package com.fang.transfer.file.client.transfer;

import com.fang.transfer.file.client.AppContext;
import com.fang.transfer.file.client.connection.MyChannelInboundHandler;
import com.fang.transfer.file.client.connection.TcpUtil;
import com.fang.transfer.file.common.RequestListener;
import com.fang.transfer.file.common.code.ClientSendCode;
import com.fang.transfer.file.common.model.TransferFileRequest;
import com.fang.transfer.file.common.model.User;

import java.io.File;
import java.util.UUID;

public class TransferService {


    public void initGUI() {
        AppContext.gui.init();
        AppContext.gui.connectionServiceUI();
        AppContext.transferService = this;
    }

    public void connectionService(String host, int port, String userName) throws InterruptedException {
        AppContext.tcpUtil = new TcpUtil(host, port);
        MyChannelInboundHandler inboundHandler = new MyChannelInboundHandler();
        AppContext.tcpUtil.connect(inboundHandler);
        this.registered(userName);
        AppContext.gui.homeUI();
    }

    private void registered(String userName) {
        User user = new User();
        user.setName(userName);
        AppContext.tcpUtil.writeAndFlush(ClientSendCode.ONLINE, user);
    }


    public void close() {
        System.exit(0);
    }


    public void serviceInfoHandler(String infoJson) throws Exception {
        String code = infoJson.substring(0, 3);
        String data = infoJson.substring(3);

        RequestListener listener = AppContext.requestListeners.get(code);
        if (listener == null) {
            System.out.println("未找到处理类code:" + code);
            return;
        }
        Object param = listener.jsonToParam(data);
        listener.handle(param);
    }


    public void sendFile(User user, String filePath) {
        if (user == null) {
            AppContext.gui.diaLogInfo("请选择传输用户");
            return;
        }

        File file = new File(filePath);
        if (!file.exists()) {
            AppContext.gui.diaLogInfo("选择的文件不存在");
            return;
        }

        if (file.isDirectory()) {
            AppContext.gui.diaLogInfo("不可以选择文件夹");
            return;
        }

        long length = file.length();
        TransferFileRequest transferFileRequest = new TransferFileRequest();
        transferFileRequest.setId(UUID.randomUUID().toString());
        transferFileRequest.setReceiveUser(user);
        transferFileRequest.setPath(filePath);
        transferFileRequest.setLength(length);
        String[] split = filePath.split("\\\\");
        transferFileRequest.setName(split[split.length - 1]);
        AppContext.tcpUtil.writeAndFlush(ClientSendCode.SEND_FILE_REQUEST, transferFileRequest);
    }

    public void receiveFile(TransferFileRequest id) {
        AppContext.tcpUtil.writeAndFlush(ClientSendCode.RECEIVE_FILE, id);
    }
}
